import { createRouter, createWebHistory } from 'vue-router'
import LayOut from '@/LayOut/index.vue'
import { isLogin, getRole } from '@/utils/user'
// 基础静态路由
const routes = [
  {
    path: '/',
    name: "LayOut",
    meta: {
      roles: "*"
    },
    component: LayOut,
    children: [
      {
        path: '/',
        
        redirect: '/dashBoard'
      },
      {
        path: 'dashBoard',
        name: "首页",
        meta: {
          roles: "*"
        },
        component: () => import('@/views/DashBoard/index.vue')
      },
      {
        path: 'cateLists',
        name: "商品分类",
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/CateLists/index.vue')
      },
      {
        path: 'itemLists',
        name: "商品列表",
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/ItemLists/index.vue')
      },
      {
        path: 'itemAdd',
        name: "新增商品",
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/ItemAdd/index.vue')
      },
      {
        path: 'itemEdit',
        name: "修改商品",
        meta: {
          roles: ['admin', 'a', 'b']
        },
        component: () => import('@/views/ItemEdit/index.vue')
      },
      {
        path: 'itemSku',
        name: "商品规格",
        meta: {
          roles: [ 'a', 'b']
        },
        component: () => import('@/views/ItemSku/index.vue')
      },
      {
        path: 'orderLists',
        meta: {
          roles: ['admin', 'a', 'b']
        },
        name: "订单列表",
        component: () => import('@/views/OrderLists/index.vue')
      },
      {
        path: 'userInfo',
        meta: {
          roles: ['a', 'b']
        },
        name: "个人中心",
        component: () => import('@/views/UserInfo/index.vue')
      }
    ]
  },
  {
    path: '/login',
    meta: {
      roles: "*"
    },
    name: "登录",
    component: () => import('@/views/LoginPage/index.vue')
  },
  {
    path:'/noauth', 
    meta: {
      roles: "*"
    },
    name: 'noauth',
    component: () => import('@/views/NoAuth/index.vue')
  },
  {
    path:'/:pathMatch(.*)*', 
    meta: {
      roles: "*"
    },
    name: '404',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes
})

router.beforeEach((to) => {
  const role = getRole();
  if (to.path === '/login') {
    if (isLogin()) {
      return "/layout"
    }
  } else {
    if (!isLogin()) {
      return '/login'
    } else {
      // 登录判断是否有权限访问
      const roles = to.meta.roles as Array<string>;
      if (to.meta.roles === '*' || roles.includes(role)){
        return true
      } else {
        return '/noauth'
      }
    }
  }
})
export default router
